package com.carworld.model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.carworld.model.base.BaseShopOrder;
import com.carworld.utils.DateUtils;
import com.carworld.utils.DicUtil;
import com.carworld.utils.weixin.HttpUtil;
import com.carworld.utils.yilianyun.Methods;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class ShopOrder extends BaseShopOrder<ShopOrder> {
	public static final ShopOrder dao = new ShopOrder().dao();

	public static Integer order_paid_status = 1;

	/********************* 缓存存储 *************************/
	// 查询订单信息
	public ShopOrder findByIdInCache(String orderId) {
		String sql = "SELECT o.* FROM shop_order o WHERE o.shop_order_id = ? ";
		return this.findFirstByCache(DicUtil.CACHE_ORDER_SHOP, orderId, sql, orderId);
	}

	// 时时查询订单信息
	public ShopOrder findOrderInfo(String orderId) {
		String sql = "SELECT o.* FROM shop_order o WHERE o.shop_order_id = ? ";
		return this.findFirst(sql, orderId);
	}

	public List<ShopOrder> getOrders(String userid) {
		String sql = " select so.* from shop_order so where so.shop_order_user= ?";
		return this.findByCache(DicUtil.CACHE_ORDER_SHOP, userid, sql, userid);
	}

	/**
	 * 根据订单状态查询已支付、未支付订单列表
	 * 
	 * @param userId
	 * @param orderStatus 0表示未结算，1为已结算
	 * @return
	 */
	public List<Record> getJsonPage(String userId, String orderStatus) {
		String sql = " SELECT o.shop_order_id,o.shop_order_user,o.shop_order_totalprice,o.shop_order_companyid,o.shop_order_phone,o.shop_order_createtime,o.shop_order_remarks"
				+ " FROM shop_order o  WHERE o.shop_order_user = ? and o.shop_order_status = ?  ORDER BY o.shop_order_createtime DESC limit 5 ";
		return Db.find(sql, userId, orderStatus);
	}

	/**
	 * 查看全部订单
	 * 
	 * @param userId
	 * @return
	 */
	public List<Record> getAllOrder(String userId) {
		String sql = " SELECT o.shop_order_id,o.shop_order_user,o.shop_order_totalprice,o.shop_order_companyid,o.shop_order_phone,o.shop_order_createtime,o.shop_order_remarks"
				+ " FROM shop_order o  WHERE o.shop_order_user = ?  ORDER BY o.shop_order_createtime DESC limit 5 ";
		return Db.find(sql, userId);
	}

	/**
	 * 4.15 得到订单信息
	 * 
	 * @param userId
	 * @param pageNumber
	 * @param pageSize
	 * @param orderStatus
	 * @return
	 */
	public Page<Record> getOrderPage(String userId, Integer pageNumber, Integer pageSize, String orderStatus) {
		List<String> whereParams = new ArrayList<String>();
		String sql = " SELECT o.shop_order_id,o.shop_order_user,o.shop_order_totalprice,o.shop_order_companyid,o.shop_order_phone,o.shop_order_createtime,o.shop_order_remarks";
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append(" FROM shop_order o ");
		sBuffer.append(" WHERE o.shop_order_user = ? ");
		whereParams.add(userId);
		this.addEqualCondition(sBuffer, whereParams, "o.shop_order_status", orderStatus);
		sBuffer.append(" ORDER BY o.shop_order_createtime DESC ");
		return Db.paginate(pageNumber, pageSize, sql, sBuffer.toString(), whereParams.toArray());
	}

	// 查询待打印订单id
	public ShopOrder getPendingOrderId(String userId) {
		String sql = "select so.*, s.name from shop_order so left join sys_office s on s.id=so.shop_order_companyid  where shop_order_user= ? and shop_order_isprint= 1 order by shop_order_updatetime desc limit 1 ";
		return this.findFirst(sql, userId);
	}
	
	
	// 查询待发送分红通知的订单
	public ShopOrder getdividendNotifyOrder(String userId) {
		String sql = "select so.* from shop_order so where so.shop_order_user= ? and so.shop_order_notify = 1 order by so.shop_order_updatetime desc limit 1 ";
		return this.findFirst(sql, userId);
	}

	// 查看最新一条待结算订单
	public ShopOrder getLatestOrder(String userId) {
		String sql = "select so.*, s.name from shop_order so left join sys_office s on s.id=so.shop_order_companyid  where shop_order_user= ? and shop_order_status= 0 order by shop_order_updatetime desc limit 1 ";
		return this.findFirst(sql, userId);
	}

	/*********************
	 * 缓存清理
	 * 
	 * @throws UnsupportedEncodingException
	 *************************/

	@Before(Tx.class)
	public ShopOrder paid(String orderId, int totalFee, String userId, int orderType) {
		System.out.println("开始更新订单");
		ShopOrder order = this.findOrderInfo(orderId);
		
		if (order == null || order.getShopOrderStatus() == order_paid_status
				|| order_paid_status.equals(order.getShopOrderStatus())) {
			System.out.println("订单失效，返回null");
			return null;
		}
		
		if ( order.getShopOrderIsprint() != 0) {
			System.out.println("订单已经不是未打印状态，返回null");
			return null;
		}

		order.setShopOrderUpdateman(userId);
		order.setShopOrderCreateman(userId);
		order.setShopOrderPaytype(orderType);
		// 更改订单支付状态
		order.setShopOrderStatus(1);
		// 更待订单打印状态
		order.setShopOrderIsprint(1);
		//更改分红通知状态
		order.setShopOrderNotify(1);
		order.update();
		
		System.out.println("订单更新成功");
		// 清除缓存
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, orderId);
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, userId + orderId);
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, userId);
		List<ShopRecord> recordList = ShopRecord.dao.getRecordList(orderId);
		StringBuffer goodsName = new StringBuffer();

		if (null == recordList) {
			System.out.println("订单出错");
			return null;
		} else {
			for (ShopRecord record : recordList) {
				BimSpares bimSpare = BimSpares.dao.getBimSparesInfo(record.getShopRecordSparesId());
				goodsName.append(record.getShopRecordNumber() + "份");
				goodsName.append(bimSpare.getSpareName() + "~");
			}
		}

		// 获取消费客户信息
		SysUser user = SysUser.dao.findByIdInCache(order.getShopOrderUser());
		// 获取门店的信息
		SysOffice shop = SysOffice.dao.findShopInCache(order.getShopOrderCompanyid());
		// 获取店长的openId
		String officerOpenId = SysUser.dao.findByIdInCache(shop.getPrimaryPerson()).getUserOpenid();

		String payment = String.valueOf(order.getShopOrderTotalprice());
		

		// 开始打印订单
		ShopOrder shopOrder = ShopOrder.dao.getPendingOrderId(user.getId());
		if (shopOrder != null && shopOrder.getShopOrderIsprint() == 1 ) {
			List<ShopRecord> orderRecord = ShopRecord.dao.getOrderDetail(String.valueOf(shopOrder.getShopOrderId()));
			StringBuffer orderParam = new StringBuffer();
			for (ShopRecord list : orderRecord) {
				orderParam.append("<FH><FW>" + list.getShopRecordNumber() + "份," + list.getStr("spareName") + ",￥"
						+ list.getShopRecordActualprice() + "</FW></FH>\r");
			}
			StringBuffer params = new StringBuffer();
			params.append("<MN>2</MN>");
			params.append("<FH2><FW2> ***茉德精品火锅***</FW2></FH2>\r");
			params.append("................................\r");
			params.append("<FH2><FW2> --在线支付--</FW2></FH2>\r");
			params.append("下单时间：" + shopOrder.getShopOrderCreatetime() + "\r");
			params.append("订单编号：" + shopOrder.getShopOrderId() + "\r");
			params.append("***************商品*************\r");
			params.append(orderParam);
			params.append("................................\r");
			params.append("<FH><FW>配送费：￥1.5</FW></FH>\r");
			params.append("<FH><FW>包装费：￥1</FW></FH>\r");
			params.append("<FH><FW>小计：￥" + shopOrder.getShopOrderTotalprice() + "</FW></FH>\r");
			params.append("<FH><FW>折扣：￥0</FW></FH>\r");
			params.append("*******************************\r");
			params.append("总价：￥" + shopOrder.getShopOrderTotalprice() + "\r");
			params.append("<FH><FW>" + user.getUserPosition() + "</FW></FH>\r");
			params.append("<FH><FW>" + user.getName() + "  " + user.getMobile() + "</FW></FH>\r");
			params.append("<FH><FW>备注：" + shopOrder.getShopOrderRemarks() + "</FW></FH>\r");
			params.append("<FH2><FW2> **茉德精品火锅**</FW2></FH2>");
			System.out.println(params.toString());
			Methods.getInstance().init("1076083105", "e4cde6f55117679d4172a57de762ce05");
			String content = null;
			try {
				content = URLDecoder.decode(params.toString(), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Methods.getInstance().addPrinter("4004608704", "237j6hy2utjm");
			String printResult = Methods.getInstance().print("4004608704", content, "0310");
			System.out.println("printResult--》" + printResult);
			if (printResult.indexOf("success") > -1) {
				System.out.println("打印成功");
				shopOrder.setShopOrderIsprint(2);
				shopOrder.update();
			}
			
		} else {
			System.out.println("没有可打印的订单");
		}
		
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, orderId);
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, userId + orderId);
		CacheKit.remove(DicUtil.CACHE_ORDER_SHOP, userId);

		if(order.getShopOrderStatus() == 1 ) {
			System.out.println("开始发送订单通知");
			System.out.println("暂时不发送给客户订单支付成功通知");
			// 通知消费者订单支付成功
			if (null != user.getUserOpenid()) {
				ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(user.getUserOpenid())// 消息接收者
						.setTemplate_id("tnghd1UZyvi95kXsLX0f_pvxx3qANqxmVLufkaRg7xo") // 支付成功的模板id
						.setUrl("http://food.3kkk.xyz/carworld_weixin/pages/page_userOrder/purchaseHistory.html")
						// 模板参数
						.add("first", "您的订单已支付成功\n").add("keyword1", orderId, "#173177")
						.add("keyword2", payment + "元", "#173177").add("keyword3", shop.getName(), "#173177")
						.add("keyword4", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("remark", "查看消费详情", "#173177").build());
				System.out.println("通知消费者模板消息结果：" + apiResult.getJson());
			}

			// 通知店长订单收益
			if (null != officerOpenId) {
				ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(officerOpenId)// 消息接收者
						.setTemplate_id("rCelFwZ1ulZvgS1AwiFVZ3LAHl84vg_au7xxJrizyU8") // 收入到账的模板id
						.setUrl("http://food.3kkk.xyz/carworld_weixin/pages/page_incomeList.html")
						.add("first", "亲爱的店长，门店有新的一笔收益到账\n").add("keyword1", payment + "元", "#173177")
						.add("keyword2", "顾客：" + user.getName() + "，商品：" + goodsName).add("keyword3", orderId, "#173177")
						.add("keyword4", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("remark", "手机号：" + user.getMobile() + "\n配送地址：" + user.getUserPosition() + "\n 订单备注:"
								+ order.getShopOrderRemarks(), "#173177")
						.build());
				System.out.println("通知店长模板消息结果：" + apiResult.getJson());
			}
			
		}
		
		return order;
	}
	
	public void dividendNotify(String orderId, String userId) {
		System.out.println("进入通知分红方法");
		ShopOrder order = this.findOrderInfo(orderId);
		if (order == null || order.getShopOrderStatus() != order_paid_status
				|| !order_paid_status.equals(order.getShopOrderStatus())) {
			System.out.println("订单未支付或不存在，不用查询分红");
			return;
		}
		if (order.getShopOrderStatus() == 1 && order.getShopOrderIsprint()== 2) {
			
			// 获取消费客户信息
			SysUser user = SysUser.dao.findByIdInCache(order.getShopOrderUser());
			SysUser shareholder = SysUser.dao.findByIdInCache(user.getUserOfShareholder());
			// 获取分红股东openId
			String shareholderIdOpenId = shareholder.getUserOpenid();
			Boolean isdividend = false;
			String dividendSumOfShareholder = null; // 调取查询分红的API
			long start,end;
			start = System.currentTimeMillis();
			String URL = "http://47.92.137.225/carWorld/doOrderCount?id=" + orderId;
			String dividendContent = null;
			try {
				dividendContent = HttpUtil.getContentFromUrl(URL);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (dividendContent != null) {
				JSONObject json = JSONObject.parseObject(dividendContent);
				System.out.println("json:" + json.toString());
				dividendSumOfShareholder = String.valueOf(json.getJSONObject("body").get("dividendGDTotal"));
				if (dividendSumOfShareholder != null) {
					isdividend = true;
				} else {
					System.out.println("暂时没有分红");
				}
				System.out.println("dividend:" + dividendSumOfShareholder);
			}
			System.out.println("isdividend--》" + isdividend);
			end = System.currentTimeMillis();  
			System.out.println("start time:" + start+ "; end time:" + end+ "; Run Time:" + (end - start) + "(ms)");
			
			
			String notificatedShareholderUrl ="http://food.3kkk.xyz/carworld_weixin/dividend/getIncomeTodyCount?shareholderId="+shareholder.getId() ;
			// 通知股东分红收入
			if (null != shareholderIdOpenId) {
				ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(shareholderIdOpenId)
						.setTemplate_id("kDim1M1Hw-uNUWP9LVvRwLz-aEnDKNybd7t5AJZ8kG0") // 收益到账通知模板id
						.setUrl(notificatedShareholderUrl)
						.add("first", "新的分红收益消息提示：\n").add("keyword1", dividendSumOfShareholder + "元", "#173177")
						.add("keyword2", "来自【" + user.getName() + "】的消费", "#173177")
						.add("keyword3", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("remark", "推广分红暂不支持查看单笔详情，后续开放。每周以excel统计数据为准", "#173177").build());
				System.out.println("通知推广专员模板消息结果：" + apiResult.getJson());
			}
			
		}else {
			System.out.println("订单未完成打印状态，返回null");
			return ;
		}
		
		
		
	}
	

	// 查询最近一周数据统计
	public Page<Record> getStatisticPage(String shopId) {
		List<String> whereParams = new ArrayList<String>();
		String select = "select CONCAT(YEAR(so.shop_order_createtime),'-',DATE_FORMAT(so.shop_order_createtime,'%m'),'-',DATE_FORMAT(so.shop_order_createtime,'%d')) days, sum(IFNULL(so.shop_order_totalprice,0) as total_income ";
		StringBuffer sBuffer = new StringBuffer(" FROM shop_order so,shop_record sr ");
		sBuffer.append(" WHERE  sr.shop_order_id = so.shop_order_id ");
		sBuffer.append(" and so.shop_order_status = 1 ");
		this.addEqualCondition(sBuffer, whereParams, "so.shop_order_companyid", shopId);
		sBuffer.append(" and so.shop_order_createtime > ? ");
		sBuffer.append(" GROUP BY days ORDER BY days DESC ");
		String date = DateUtils.getLastSevenDay(); // 最近7天
		return Db.paginate(1, 7, select, sBuffer.toString(), date);
	}

	// 按照起止时间查询营业额
	public Page<Record> getPageOfIncome(String shopId, String beginTime, String endTime) {
		List<String> whereParams = new ArrayList<String>();
		String sql = "select IFNULL(sum(so.shop_order_totalprice,0.00)) as sumIncome ";
		StringBuffer sBuffer = new StringBuffer(" FROM shop_order so,shop_record sr ");
		sBuffer.append(" WHERE  sr.shop_order_id = so.shop_order_id ");
		sBuffer.append(" and so.shop_order_status = 1 ");
		this.addEqualCondition(sBuffer, whereParams, "so.shop_order_companyid", shopId);
		this.addNotLessThanCondition(sBuffer, whereParams, "so.shop_order_createtime", beginTime);
		this.addNotMoreThanCondition(sBuffer, whereParams, "so.shop_order_createtime", endTime);
		return Db.paginateByCache(DicUtil.CACHE_ORDER_SHOP, shopId + beginTime + endTime, 1, 1, sql, sBuffer.toString(),
				whereParams.toArray());
	}

	// 根据年月日查询营业额
	public Page<Record> getSumIncomeByTime(String shopId, String time) {
		List<String> whereParams = new ArrayList<String>();
		String sql = "selectIFNULL(sum(so.shop_order_totalprice,0.00)) as sumIncome ";
		StringBuffer sBuffer = new StringBuffer(" FROM shop_order so,shop_record sr ");
		sBuffer.append(" WHERE  sr.shop_order_id = so.shop_order_id ");
		sBuffer.append(" and so.shop_order_status = 1 ");
		this.addEqualCondition(sBuffer, whereParams, "so.shop_order_companyid", shopId);
		this.addLikeCondition(sBuffer, whereParams, "so.shop_order_createtime", time);
		return Db.paginateByCache(DicUtil.CACHE_ORDER_SHOP, shopId + time, 1, 1, sql, sBuffer.toString(),
				whereParams.toArray());
	}

	// 店长查看门店分红收入
	public ShopOrder getShopIncomeSum(String userId) {
		String sql = "select IFNULL(sum(so.shop_order_totalprice,0.00)) as sumIncome FROM shop_order sr left join sys_office se on se.id= sr.shop_order_companyid  WHERE  se.PRIMARY_PERSON = ? ";
		return this.findFirstByCache(DicUtil.CACHE_DIVIDEND_RECORD, userId, sql, userId);
	}

}
